package com.lxq.listener;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * @author 龙小虬
 * @date 2021/3/24 14:57
 */
public class MySpringApplicationRunListeners implements SpringApplicationRunListener {

    private final SpringApplication application;

    private final String[] args;

    public MySpringApplicationRunListeners(SpringApplication application, String[] args) {
        this.application = application;
        this.args = args;
    }

    @Override
    public void starting() {
        System.out.println(">>>>>starting<<<<<");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        // 先读取配置文件到程序中，然后放入SpringBoot中
        Properties properties = new Properties();
        try {
            // 1. 读取我们的my.properties文件
            properties.load(new InputStreamReader(this.getClass().getClassLoader().
                    getResourceAsStream("my.properties"), "GB2312"));
            // 2. 读取名称名称为my
            PropertySource propertySource = new PropertiesPropertySource("my", properties);
            //3. 将资源添加到项目中
            MutablePropertySources propertySources = environment.getPropertySources();
            //4. 通过api接口可以将配置文件读取 到SpringBoot项目中
            propertySources.addLast(propertySource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
